package com.chen.pfm.slice;

import com.chen.pfm.DateStatisticsAbility;
import com.chen.pfm.ResourceTable;
import com.chen.pfm.entity.Account;
import com.chen.pfm.entity.DisplayBill;
import com.chen.pfm.provider.AccountProvider;
import com.chen.pfm.provider.DisplayBillProvider;
import com.chen.pfm.utils.AccountDBUtil;
import com.chen.pfm.utils.DateUtils;
import com.chen.pfm.utils.MyToast;
import com.chen.pfm.utils.MyUtil;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.DataAbilityRemoteException;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.Component;
import ohos.agp.components.ListContainer;
import ohos.agp.components.Text;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;


public class DateStatisticsAbilitySlice extends AbilitySlice {
    private static String CurrentClassName = "DateStatisticsAbilitySlice";
    static final HiLogLabel LABEL = new HiLogLabel(HiLog.LOG_APP, 0x2022001, CurrentClassName);
    private String operation;
    DisplayBillProvider displayBillProvider;
    ListContainer listContainer;
    DisplayBill item;//触发账单的元素
    int itemPosition;//触发事件的元素项位置
    DisplayBill displayBill;//单一被处理的
    Text DateTimeText;
    Text title;
    Text bill_income;
    Text bill_expend;
    List<DisplayBill> displayBills;
    String DateTime = "";
    double totalIncome = 0.0;
    double expenditure = 0.0;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_date_statistics);

        // 获取ListContainer
        listContainer = (ListContainer) findComponentById(ResourceTable.Id_account_ListContainer);
        bill_income = (Text) findComponentById(ResourceTable.Id_bill_income);
        bill_expend = (Text) findComponentById(ResourceTable.Id_bill_expend);
        //这里可以做判空检测
        if (listContainer == null || bill_income == null || bill_expend == null) {
            HiLog.error(LABEL, "组件加载失败！");
            return;
        }
        operation = intent.getStringParam("operation");
        title = (Text) findComponentById(ResourceTable.Id_title);
        title.setText(operation + "账单统计");
        DateTime = intent.getStringParam("StatisticsDateTime");

        if (operation != null) {
            HiLog.info(LABEL, "传输来的操作值为：" + operation);
        }
        //日期

        DateTimeText = (Text) findComponentById(ResourceTable.Id_StatisticsDateTime);
        HiLog.error(LABEL, "传输来的时间值" + DateTime);
        if (DateTimeText != null && DateTime != null) {
            DateTimeText.setText(DateTime);

            try {
                if ("近七天".equals(operation)) {
                    displayBills = MyUtil.queryDisplayBillByPastSevenDays(this);
                    DateTimeText.setText(operation);
                } else {
                    displayBills = MyUtil.queryDisplayBillByArtime(this, DateTime);
                }

            } catch (DataAbilityRemoteException e) {
                HiLog.error(LABEL, "displayBills查询失败！" + displayBills);
                e.printStackTrace();
            }

        } else {
            HiLog.error(LABEL, "传输来的操作值为空");
        }

        //返回按钮监听
        findComponentById(ResourceTable.Id_goback_btn).setClickedListener((component) -> {
            terminate();
        });
        if (displayBills != null) {

            FulshData();

        } else {
            MyToast.showMyToast(this, "传输来的渲染数据为空");
            return;
        }

    }

    /**
     *
     */
    public void FulshData() {
        //账单按照记录时间降序排序
        Collections.sort(displayBills, new Comparator<DisplayBill>() {
            @Override
            public int compare(DisplayBill o1, DisplayBill o2) {
                //这里使用时间字段排序 如果要用其他字段直接从bean实体中取
                return o2.getRecordTime().compareTo(o1.getRecordTime());
                //上面使用的是降序排序，如果正序 直接使用o1-o2即可
            }
        });
        getUITaskDispatcher().asyncDispatch(() -> {
            totalIncome = MyUtil.getTotalAmoney(displayBills, 2);//总收入
            bill_income.setText(MyUtil.getStrBalance(totalIncome));
            expenditure = MyUtil.getTotalAmoney(displayBills, 1);//总支出
            bill_expend.setText(MyUtil.getStrBalance(expenditure));
            //需要的数据
            HiLog.error(LABEL, "计算得到的值：" + displayBills.toString());
            displayBillProvider = new DisplayBillProvider(displayBills, this);
            listContainer.setItemProvider(displayBillProvider);
            //点击进入详情页面
            listContainer.setItemClickedListener((container, component, i, id) -> {
                item = (DisplayBill) listContainer.getItemProvider().getItem(i);
                itemPosition = i;
                if (item == null) {
                    return;
                }
                //跳转
                Intent intent = new Intent();

                intent.setParam("Aid", item.getAid());
                presentForResult(new BillDetailsSlice(), intent, 1004);

            });
        });
    }

    //返回触发事件
    @Override
    protected void onResult(int requestCode, Intent resultIntent) {
        super.onResult(requestCode, resultIntent);
        if (requestCode == 1004) {
            if (resultIntent != null) {
                String op = resultIntent.getStringParam("op");
                if (op == null) {
                    return;
                }
                getUITaskDispatcher().asyncDispatch(() -> {
                    totalIncome = MyUtil.getTotalAmoney(displayBills, 2);//总收入
                    bill_income.setText(MyUtil.getStrBalance(totalIncome));
                    expenditure = MyUtil.getTotalAmoney(displayBills, 1);//总支出
                    bill_expend.setText(MyUtil.getStrBalance(expenditure));
                });
                //处理
                if (op.equals("del")) {
                    displayBills.remove(itemPosition);
                    //数据改变监听事件
                    listContainer.setBindStateChangedListener(new Component.BindStateChangedListener() {
                        @Override
                        public void onComponentBoundToWindow(Component component) {
                            // ListContainer初始化时数据统一在provider中创建，不直接调用这个接口；

                            displayBillProvider.notifyDataSetItemRemoved(itemPosition);
                        }

                        @Override
                        public void onComponentUnboundFromWindow(Component component) {
                        }
                    });
                } else if (op.equals("update")) {
                    String aid = resultIntent.getStringParam("aid");
                    try {
                        displayBill = MyUtil.queryDisplayBillByAid(this, aid);
                    } catch (DataAbilityRemoteException e) {
                        e.printStackTrace();
                    }
                    displayBills.remove(itemPosition);
                    displayBills.add(itemPosition, displayBill);
                    //数据改变监听事件
                    listContainer.setBindStateChangedListener(new Component.BindStateChangedListener() {
                        @Override
                        public void onComponentBoundToWindow(Component component) {

                            displayBillProvider.notifyDataSetItemChanged(itemPosition);
                        }

                        @Override
                        public void onComponentUnboundFromWindow(Component component) {
                        }
                    });
                } else {

                }

                setResult(resultIntent);
            }


        }
    }
}
